package com.xiaoshuidi.cloud.module.system.dal.mysql.oauth2;

import com.baomidou.mybatisplus.extension.handlers.JacksonTypeHandler;
import com.xiaoshuidi.cloud.framework.mybatis.core.mapper.BaseMapperX;
import com.xiaoshuidi.cloud.framework.mybatis.core.query.LambdaQueryWrapperX;
import com.xiaoshuidi.cloud.module.system.dal.dataobject.oauth2.OAuth2AccessTokenWithUserInfo;
import com.xiaoshuidi.cloud.module.system.dal.dataobject.oauth2.OAuth2RefreshTokenDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface OAuth2RefreshTokenMapper extends BaseMapperX<OAuth2RefreshTokenDO> {

    default int deleteByRefreshToken(String refreshToken) {
        return delete(new LambdaQueryWrapperX<OAuth2RefreshTokenDO>()
                .eq(OAuth2RefreshTokenDO::getRefreshToken, refreshToken));
    }

    default OAuth2RefreshTokenDO selectByRefreshToken(String refreshToken) {
        return selectOne(OAuth2RefreshTokenDO::getRefreshToken, refreshToken);
    }

    @Select("select t.*, ifnull(u.nickname,ut.nickname) as nickname1, u.dept_id, ifnull(u.mobile, ut.mobile) as mobile1 " +
            "from system_oauth2_refresh_token t " +
            "left join system_users u on t.user_id = u.id " +
            "left join system_oauth2_access_token ut on ut.refresh_token = t.refresh_token " +
            "where t.refresh_token = #{refreshToken} limit 1")
    @Results({
            @Result(property = "id", column = "id"),
            @Result(property = "refreshToken", column = "refresh_token"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "userType", column = "user_type"),
            @Result(property = "clientId", column = "client_id"),
            @Result(property = "scopes", column = "scopes", typeHandler = JacksonTypeHandler.class),
            @Result(property = "expiresTime", column = "expires_time"),
            @Result(property = "nickname", column = "nickname1"),
            @Result(property = "deptId", column = "dept_id"),
            @Result(property = "mobile", column = "mobile1"),
    })
    OAuth2AccessTokenWithUserInfo selectByRefreshTokenWithUserInfo(String refreshToken);
}
